// threadpool.hpp
#pragma once
#include <string>
#include <vector>
#include <queue>
#include <pthread.h>
#include <unistd.h>

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template <class T>
class ThreadPool
{
    static const int defaultnum = 5;
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Tsleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (const auto & ti : _threads)
        {
            if(ti.tid == tid) return ti.name;
        }
        return nullptr;
    }
public:
    ThreadPool(int num = defaultnum)
        :_threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T>*>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();
            while (tp->IsQueueEmpty())
            {
                tp->Tsleep();
            }
            T t = tp->pop();
            tp->Unlock();

            t();
            std::cout << name << "run, result: " << t.GetResult() << std::endl;
        }
        return nullptr;
    }
    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; ++i)
        {
            _threads[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    }
    T pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    void Push(const T &t)
    {
        Lock();
        _tasks.push(t);
        Wakeup();
        Unlock();
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _tasks;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};